package com.hllxd.hism.star.basic.service.service;

import com.alibaba.fastjson.JSON;
import com.hllxd.hism.star.basic.service.util.TimeUtil;
import com.hllxd.hism.star.basic.service.dao.mapper.mis.UserMapper;
import com.hllxd.hism.star.basic.service.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xiyong.lxy
 * @date 2020-10-12 16:51
 * v1/user/userInfo.do
 */
@Slf4j
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public UserInfo userInfo(String phoneNumber) {
        log.info("request params: {}", phoneNumber);
        List<UserInfo> items = userMapper.getUserInfo(phoneNumber);
        int size = items.size();
        if(size>1 || size==0) {
            log.warn("user is not exist. {}", phoneNumber);
            return null;
        }
        return items.get(0);
    }

    @Override public UserInfo getUser(Long id) {
        return userMapper.getUser(id);
    }

    @Override
    public Boolean delUser(Long id) {
        return userMapper.deleteUser(id.toString());
    }

    @Override public Long setUser(UserInfo entity) {
        log.info("set param: {}", JSON.toJSONString(entity));
        if(entity.id==null || entity.id==0) {
            entity.userNo = "U" + TimeUtil.currentTimeHllDT();
            return userMapper.insertUser(entity);
        } else {
            return userMapper.updateUser(entity);
        }
    }

    @Override public Long resetPassword(UserInfo entity, String password0) {
        log.info("set param: {}", JSON.toJSONString(entity));
        UserInfo user0 = userMapper.getPassword(entity.id);
        // 需要与旧的密码对比
        if(user0==null) {
            log.warn("select user info failed.");
            return -1L;
        }
        String userName = user0.userName;
        String password = user0.password;
        if(userName==null || password==null) {
            log.warn("select user info failed. {}, {}", userName, password);
            return -1L;
        }
        if(userName.equals(entity.userName) && password.equals(password0)) {
            return userMapper.resetPassword(entity);
        }else {
            log.warn("username or password is invalid. {}, {}, {}.", userName, password, password0);
        }
        return -2L;
    }

    @Override public List<UserInfo> userList() {
        return userMapper.listUserInfo();
    }

    @Override
    public List<UserInfo> pingDetail(String userId) {

//        if("developer".equals(userId)) {
//            userId = "lixiyong01";
//        }
        List<UserInfo> items = userMapper.pingDetail(userId);
        int size = items.size();
        if(size>1 || size==0) {
            log.warn("user is not exist. {}", userId);
            return null;
        }
        return items;
    }
}
